/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.mobao.marshal;

import com.acooly.core.utils.Encodes;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiMarshalSupport;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.api.util.XStreams;
import com.acooly.module.openapi.client.provider.mobao.domain.MoBaoResponse;
import com.acooly.module.safety.signature.SignTypeEnum;
import com.acooly.module.safety.support.KeyStoreInfo;
import com.thoughtworks.xstream.XStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhangpu
 */
public class MobaoResponseUnmarshal extends ApiMarshalSupport implements ApiUnmarshal<MoBaoResponse, String> {

    private static final Logger logger = LoggerFactory.getLogger(MobaoResponseUnmarshal.class);

    private MessageFactory messageFactory;

    protected static KeyStoreInfo keystore = new KeyStoreInfo();

    @SuppressWarnings("unchecked")
    @Override
    public MoBaoResponse unmarshal(String message, String serviceName) {
        try {
            String[] fields = Strings.split(message, ",");
            String xml = Strings.substringAfter(fields[0], "message=");
            String signature = Strings.substringAfter(fields[1], "signature=");
            getSigner(SignTypeEnum.Cert).verify(signature, keystore, xml);
            String xmlMessage = null;
            xmlMessage = new String(Encodes.decodeBase64(xml), "UTF-8");
            logger.info("响应 XML:{}", Strings.substringAfter(xmlMessage, "?>"));
            return doUnmarshall(xmlMessage, serviceName);
        } catch (Exception e) {
            throw new ApiClientException("解析响应报文错误:" + e.getMessage());
        }

    }

    protected MoBaoResponse doUnmarshall(String xml, String serviceName) {
        MoBaoResponse response = (MoBaoResponse) messageFactory.getResponse(serviceName);
        XStream xstream = XStreams.getXStream();
        xstream.alias("MoBaoAccount", response.getClass());
        response = (MoBaoResponse) xstream.fromXML(xml, response);
        return response;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }

}
